package lemon.dog.middleware.interceptor;

import com.alibaba.fastjson2.JSON;
import lemon.dog.common.ErrorEnum;
import lemon.dog.common.R;
import lemon.dog.context.BaseContext;
import lemon.dog.util.JwtUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("x-token");
        if(StringUtils.isEmpty(token) || !JwtUtil.checkToken(token)) {
            response.setStatus(401);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().write(JSON.toJSONString(R.error(ErrorEnum.USER_NOT_AUTHORITY)));
            response.getWriter().close();
            return false;
        }
        BaseContext.setToken(token);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.remove();
    }
}
